package com.wmz.picture.aop;

import com.wmz.picture.annotation.AuthCheck;
import com.wmz.picture.exception.BusinessException;
import com.wmz.picture.exception.ErrorCode;
import com.wmz.picture.model.entity.User;
import com.wmz.picture.model.enums.UserRoleEnum;
import com.wmz.picture.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author lihechun
 * @version 1.0
 * @description: 权限校验切面
 * @date: 2024/12/15 13:59
 */
@Aspect
@Component
public class AuthInterceptor {
    @Resource
    private UserService userService;

    /**
     * 执行拦截
     * @param joinPoint 切入点
     * @param authCheck 权限校验注解
     * @return 通过校验返回结果，未通过校验则抛出异常
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        // 获取注解中的参数
        String mustRole = authCheck.mustRole();
        // 获取request请求
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 通过request请求获取当前用户
        User loginUser = userService.getLoginUser(request);
        // 必须具有的权限
        UserRoleEnum mustUserRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
        // 如果不需要权限，直接放行
        if(mustUserRoleEnum == null) {
            return joinPoint.proceed();
        }
        // 以下为：必须具有权限才能访问
        // 获取当前用户的权限
        UserRoleEnum loginUserRole = UserRoleEnum.getEnumByMapValue(loginUser.getUserRole());
        // 如果没有权限，拒绝
        if(loginUserRole == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 管理员权限放行所有
        if(UserRoleEnum.ADMIN.equals(loginUserRole)) {
            return joinPoint.proceed();
        }
        // 要求必须有管理员权限，但用户没有管理员权限，则拒绝
        if(UserRoleEnum.ADMIN.equals(mustUserRoleEnum) && !UserRoleEnum.ADMIN.equals(loginUserRole)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 要求必须有会员权限，但用户没有会员权限，则拒绝
        if(UserRoleEnum.VIP.equals(mustUserRoleEnum) && !UserRoleEnum.VIP.equals(loginUserRole)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return joinPoint.proceed();
    }
}
